import getUserTempId from "@/utils/userTempld"
import { reqLogin,reqUserInfo,reqLogout  } from "@/api";
const  state ={
    userTempId:getUserTempId(),
    token:localStorage.getItem("token")||"",
    userInfo:{
      nickName:""
    },
};
const mutations = {
    SET_TOKEN_STATE(state, payload) {
      // console.log(payload);
        state.token = payload.token;
      },
    SET_USERINFO_STATE(state, payload) {
        state.userInfo = payload.userInfo;
      },
    RESET_USERINFO_STATE(state) {
        state.token = "";
        state.userInfo = { nickName: "" };
        localStorage.removeItem("token");
      },  
}
const actions={
    async getToken({ commit },userInfo) {
        try {
          const result = await reqLogin(userInfo);
          localStorage.setItem("token", result.token);
          commit("SET_TOKEN_STATE", { token: result.token });
        } catch (e) {
          return Promise.reject(e)
        }
      },
      async getUserInfo({ commit }) {
        try {
          const result = await reqUserInfo();
          // console.log(result);
          commit("SET_USERINFO_STATE", { userInfo: result });
        } catch (e) {
          return Promise.reject(e.message)
        }
      },
      getResetUser({ commit }) {
        commit("RESET_USERINFO_STATE");
      },
      async getLogout({commit}){
        try{
            await reqLogout();
            // 退出成功以后，清空用户信息
            commit("RESET_USERINFO_STATE")
        }catch(e){
            return Promise.reject(e);
        }
      }
    };

export default {
    namespaced:true,
    state,
    mutations,
    actions
}